#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>

extern void Sync(char *src, char *dest);
extern void syncAB(char *src, char *dest);
extern void backup(char *src, char *dest);

void ToSame(char *src, char *dest)
{
	while (1)
	{
		int option;
		printf("╔----------------------------╗\n");
		printf("  $ 同步选项 $\n");
		printf("   1 # B目录同步A目录\n");
		printf("   2 # A目录同步B目录\n");
		printf("   3 # AB目录同时同步，取并集\n");
		printf("   0 # 返回\n");
		printf("╚----------------------------╝\n");
		printf("       请选择：");
		scanf("%d", &option);
		if (option == 0)
			break;
		switch (option)
		{
		case 1:
			Sync(src, dest);
			break;
		case 2:
			Sync(dest, src);
			break;
		case 3:
			syncAB(src, dest);
			break;
		}
	}
}

void doBackup()
{
	DIR *dir_src = NULL;
	DIR *dir_dest = NULL;
	char src_path[PATH_MAX] = {0};
	char dest_path[PATH_MAX] = {0};

	while (1)
	{
		printf("  请输入需要备份目录的路径：");
		scanf("%s", src_path);
		dir_src = opendir(src_path);
		if (dir_src != NULL)
			break;
		else
		{
			perror("src:");
			printf("  请重新输入！\n");
		}
	}

	while (1)
	{
		printf("  请输入目标目录的路径：");
		scanf("%s", dest_path);
		dir_dest = opendir(dest_path);
		if (dir_dest != NULL)
			break;
		else
		{
			printf("  输入错误，请重新输入！\n");
		}
	}

	printf("  开始文件备份\n");
	backup(src_path, dest_path);
	printf(" 备份完成\n");
}

void doSync()
{
	DIR *dir_src = NULL;
	DIR *dir_dest = NULL;
	char src_path[PATH_MAX] = {0};
	char dest_path[PATH_MAX] = {0};

	while (1)
	{
		printf("  请输入需要同步目录的路径：");
		scanf("%s", src_path);
		dir_src = opendir(src_path);
		if (dir_src != NULL)
			break;
		else
		{
			perror("src:");
			printf("  请重新输入！\n");
		}
	}

	while (1)
	{
		printf("  请输入目标目录的路径：");
		scanf("%s", dest_path);
		dir_dest = opendir(dest_path);
		if (dir_dest != NULL)
			break;
		else
		{
			printf("  输入错误，请重新输入！\n");
		}
	}

	printf("  开始文件同步\n");
	ToSame(src_path, dest_path);
	printf("  同步完成\n");
}

int main()
{
	while (1)
	{
		int option;
		printf("╔----------------------------╗\n");
		printf("  $ linux 下文件备份和同步 $\n");
		printf("   1 # 文件备份\n");
		printf("   2 # 文件同步\n");
		printf("   0 # 退出\n");
		printf("╚----------------------------╝\n");
		printf("       请选择：");
		scanf("%d", &option);
		if (option == 0)
			break;
		switch (option)
		{
		case 1:
			doBackup();
			break;
		case 2:
			doSync();
			break;
		}
	}
	return 0;
}
